package com.ruoyi.business.controller;

import java.math.BigDecimal;
import java.time.Duration;
import java.util.Date;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.util.StrUtil;
import com.google.common.collect.Sets;
import com.ruoyi.business.domain.Task;
import com.ruoyi.business.model.CascaderModel;
import com.ruoyi.business.response.ApiPlanLayerRes;
import com.ruoyi.business.service.*;
import com.ruoyi.common.utils.RedisUtils;
import com.ruoyi.common.utils.SecurityUtils;
import org.springframework.security.access.prepost.PreAuthorize;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Map;

import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.business.domain.ResearchPlan;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

import static com.ruoyi.business.constants.JetCacheConstant.PLAN_LAYER_CACHE_NAME;


/**
 * 调研计划Controller
 *
 * @author Eric
 * @date 2024-03-20
 */
@RestController
@RequestMapping("/business/researchPlan")
public class ResearchPlanController extends BaseController {
    @Resource
    private IResearchPlanService researchPlanService;
    @Resource
    private IDataServerService dataServerService;
    @Resource
    private ITaskService taskService;
    @Resource
    private ITaskUserTrajectoryService taskUserTrajectoryService;
    @Resource
    private CommonDataService commonDataService;

    /**
     * 查询调研计划列表
     */
    @PreAuthorize("@ss.hasPermi('business:researchPlan:list')")
    @GetMapping("/list")
    public TableDataInfo list(ResearchPlan researchPlan) {
        startPage();
        List<ResearchPlan> list = researchPlanService.list(Wrappers.lambdaQuery(ResearchPlan. class).
        setEntity( researchPlan));
        return getDataTable(list);
    }

    /**
     * 导出调研计划列表
     */
    @PreAuthorize("@ss.hasPermi('business:researchPlan:export')")
    @Log(title = "调研计划", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ResearchPlan researchPlan) {
        List<ResearchPlan> list = researchPlanService.list(Wrappers.lambdaQuery(ResearchPlan. class).
        setEntity( researchPlan));
        ExcelUtil<ResearchPlan> util = new ExcelUtil<ResearchPlan>(ResearchPlan. class);
        util.exportExcel(response, list, "调研计划数据");
    }


    /**
     * 获取调研计划详细信息
     */
    @PreAuthorize("@ss.hasPermi('business:researchPlan:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(researchPlanService.getResearchPlanInfo(id));
    }

    /**
     * 新增调研计划
     */
    @PreAuthorize("@ss.hasPermi('business:researchPlan:add')")
    @Log(title = "调研计划", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ResearchPlan researchPlan) {
        researchPlan.setCreateBy(getUsername());
        researchPlan.setCreateTime(new Date());
        return toAjax(researchPlanService.savePlan(researchPlan));
    }

    /**
     * 修改调研计划
     */
    @PreAuthorize("@ss.hasPermi('business:researchPlan:edit')")
    @Log(title = "调研计划", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ResearchPlan researchPlan) {
        researchPlan.setUpdateBy(getUsername());
        researchPlan.setUpdateTime(new Date());
        return toAjax(researchPlanService.updatePlan(researchPlan));
    }

    /**
     * 删除调研计划
     */
    @PreAuthorize("@ss.hasPermi('business:researchPlan:remove')")
    @Log(title = "调研计划", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        List<Long> idList = Arrays.asList(ids);
        long count = taskService.count(Wrappers.lambdaQuery(Task.class).in(Task::getResearchPlanId, idList));
        if (count > 0) {
            return AjaxResult.error("调研计划下存在任务，不允许删除。");
        }
        if (researchPlanService.removeBatchByIds(idList)) {
            for (Long id : idList) {
                String cacheKey = StrUtil.format("{}{}", PLAN_LAYER_CACHE_NAME, id);
                RedisUtils.deleteObject(cacheKey);
            }

            return toAjax(true);
        }
        return toAjax(false);
    }

    @GetMapping("/select")
    public AjaxResult select() {
        List<Map<String, Object>> list = researchPlanService.select();
        return AjaxResult.success(list);
    }


    @GetMapping("/data/server/select")
    public AjaxResult dataServerSelect() {
        List<CascaderModel> list = dataServerService.dataServerSelect();
        return AjaxResult.success(list);
    }

    @GetMapping("/trajectory")
    public AjaxResult getTrajectory(@RequestParam Long researchPlanId, Long userId, Integer version){
        Map<String, List<List<BigDecimal>>> list = taskUserTrajectoryService.getTrajectoryListAdmin(researchPlanId, userId, version);
        return AjaxResult.success(list);
    }

    @PreAuthorize("@ss.hasPermi('business:researchPlan:sync-data-server')")
    @Log(title = "调研计划", businessType = BusinessType.UPDATE)
    @PostMapping("/syncDataServer")
    public AjaxResult syncDataServer() {
        commonDataService.syncDataServer();
        return AjaxResult.success();
    }
}
